import Taro from '@tarojs/taro'
import env from '../utils/env.json'
import interceptors from './interceptors'
import {getGlobalData} from '../utils/global'

console.log(getGlobalData('loginVO'), 'gloal')

interceptors.forEach(interceptorItem => Taro.addInterceptor(interceptorItem))

interface HttpRequest<T = any> extends Partial<Taro.request.Option<T>> {
  params?: Record<string, any>
  contentType?: 'application/json'
}
const getRequestUrl = (url: string, params: any) => {
  let requestUrl = env.httpBaseUrl + url
  let str = ''
  if (params) {
    let paramArr = Object.keys(params).map(key => `${key}=${encodeURIComponent(params[key])}`)
    for (let i = 0; i < paramArr.length; i++) {
      if (i == 0) {
        str += '?' + `${paramArr[i]}`
      } else {
        str += '&' + `${paramArr[i]}`
      }
    }
    // requestUrl += requestUrl.includes('?') ? '&' : '?' + paramArr.join('=')
    requestUrl += str
  }
  return requestUrl
}
const doRequest = async (request: HttpRequest) => {
  let {url, params, method, data, contentType = 'application/json'} = request
  let requestUrl = getRequestUrl(url, params)
  const option = {
    url: requestUrl,
    method: method,
    data: data && data.params ? data.params : data,
    header: {
      'content-type': contentType,
      tenantId: 'lovelorn',
      devType: 4,
      // userId: Taro.getStorageSync('loginVO')
      //   ? Taro.getStorageSync('loginVO').user.userId
      //   : '489504064061440',
      // token: Taro.getStorageSync('loginVO')
      //   ? Taro.getStorageSync('loginVO').authInfo.token
      //   : 'lXTjC6GGWB501592457092494',
      token: getGlobalData('loginVO')
        ? getGlobalData('loginVO').authInfo.token
        : Taro.getStorageSync('loginVO') && Taro.getStorageSync('loginVO').authInfo.token,
      userid: getGlobalData('loginVO')
        ? getGlobalData('loginVO').user.userId
        : Taro.getStorageSync('loginVO') && Taro.getStorageSync('loginVO').user.userId,
    },
  }
  return await Taro.request(option)
}

// export default new httpRequest()
export function httpPost(url: string, data?: any, congfig?: HttpRequest) {
  return doRequest({...congfig, url, data, method: 'POST'})
}
export function httpGet(url: string, congfig?: HttpRequest) {
  return doRequest({...congfig, url, method: 'GET'})
}
export function httpDelete(url: string, data?: any, congfig?: HttpRequest) {
  return doRequest({...congfig, url, data, method: 'DELETE'})
}
export function httpPut(url: string, data?: any, congfig?: HttpRequest) {
  return doRequest({...congfig, url, data, method: 'PUT'})
}
